<template>
  <div class="app-container">

    <el-form style="margin-top: 30px" :model="queryParams" ref="infoQueryForm" size="small" :inline="true"
             width="68px">
      <el-form-item>
        <span style="font-size: 20px">{{ parseInt(parseTime(queryParams.createTime, '{m}')) }} 月工资条</span>
      </el-form-item>
      <el-form-item style="margin-left: 10px">
        <el-date-picker
          v-model="queryParams.createTime"
          :editable="false"
          :clearable="false"
          @change="allQuery"
          value-format="yyyy-MM"
          type="month"
          placeholder="选择月份">
        </el-date-picker>
      </el-form-item>
      <el-form-item prop="all">
        <el-input
          v-model="queryParams.all"
          placeholder="支持姓名工号查询"
          clearable
          @keyup.enter.native="allQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="allQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="indexCollectList"
              v-loading="loading"
              @selection-change="handleSelectionChange" border style="width: 100%">
      <el-table-column fixed align="center" type="selection" width="55"></el-table-column>
      <el-table-column align="center" width="120" prop="empName" label="姓名">
        <template slot-scope="scope">
          <span v-if="scope.row.empName === undefined ||scope.row.empName === null">-</span>
          <span v-else>{{ scope.row.empName }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="100" prop="jobNo" label="工号">
        <template slot-scope="scope">
          <span v-if="scope.row.jobNo === undefined ||scope.row.jobNo === null">-</span>
          <span v-else>{{ scope.row.jobNo }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120" prop="deptName" label="部门">
        <template slot-scope="scope">
          <span v-if="scope.row.deptName === undefined ||scope.row.deptName === null">-</span>
          <span v-else>{{ scope.row.deptName }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120" :show-overflow-tooltip="true" prop="positionApplied"
                       label="职务">
        <template slot-scope="scope">
          <span v-if="scope.row.positionApplied === undefined ||scope.row.positionApplied === null">-</span>
          <span v-else>{{ scope.row.positionApplied }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120" prop="empStatus" label="员工状态">
        <template slot-scope="scope">
          <span v-if="scope.row.empStatus === 3">试用</span>
          <span v-if="scope.row.empStatus === 4">正式</span>
          <span v-if="scope.row.empStatus === 6">离职</span>
        </template>
      </el-table-column>
      <!--<el-table-column align="center" width="120" :show-overflow-tooltip="true" prop="enterprise"
                       label="公司">
        <template slot-scope="scope">
          <span v-if="scope.row.enterprise === undefined ||scope.row.enterprise === null">-</span>
          <span v-else>{{ scope.row.enterprise }}</span>
        </template>
      </el-table-column>-->
      <el-table-column align="center" width="120" prop="workNature" label="工作性质">
        <template slot-scope="scope">
          <span v-if="scope.row.workNature === undefined ||scope.row.workNature === null">-</span>
          <span v-else>{{ scope.row.workNature }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120" prop="verifyAgoSalary" label="工资总核对额">
        <template slot-scope="scope">
          <span v-if="scope.row.verifyAgoSalary === undefined ||scope.row.verifyAgoSalary === null">-</span>
          <span v-else>{{ parseFloat(scope.row.verifyAgoSalary).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120" prop="basePay" label="基本工资">
        <template slot-scope="scope">
          <span v-if="scope.row.basePay === undefined ||scope.row.basePay === null">-</span>
          <span v-else>{{ parseFloat(scope.row.basePay).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120" prop="gradePay" label="级别工资">
        <template slot-scope="scope">
          <span v-if="scope.row.gradePay === undefined ||scope.row.gradePay === null">-</span>
          <span v-else>{{ parseFloat(scope.row.gradePay).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120" prop="meritPay" label="绩效工资">
        <template slot-scope="scope">
          <span v-if="scope.row.meritPay === undefined ||scope.row.meritPay === null">0</span>
          <span v-else>{{ parseFloat(scope.row.meritPay).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120" prop="practicalSalary" label="当月实际工资额">
        <template slot-scope="scope">
          <span v-if="scope.row.practicalSalary === undefined ||scope.row.practicalSalary === null">-</span>
          <span v-else>{{ parseFloat(scope.row.practicalSalary).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120" prop="coefficient" label="系数">
        <template slot-scope="scope">
          <span v-if="scope.row.coefficient === undefined ||scope.row.coefficient === null">-</span>
          <span v-else>{{ parseFloat(scope.row.coefficient).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120" prop="royaltiesMoney" label="提成">
        <template slot-scope="scope">
          <span v-if="scope.row.royaltiesMoney === undefined ||scope.row.royaltiesMoney === null">-</span>
          <span v-else>{{ parseFloat(scope.row.royaltiesMoney).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120" prop="bonus" label="奖金">
        <template slot-scope="scope">
          <span v-if="scope.row.bonus === undefined ||scope.row.bonus === null">-</span>
          <span v-else>{{ parseFloat(scope.row.bonus).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120" prop="housingAllowance" label="电脑/住房补贴">
        <template slot-scope="scope">
          <span v-if="scope.row.housingAllowance === undefined ||scope.row.housingAllowance === null">-</span>
          <span v-else>{{ parseFloat(scope.row.housingAllowance).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120" prop="transportationAllowance" label="交通补贴">
        <template slot-scope="scope">
          <span
            v-if="scope.row.transportationAllowance === undefined ||scope.row.transportationAllowance === null">-</span>
          <span v-else>{{ parseFloat(scope.row.transportationAllowance).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120" prop="overtime" label="加班补贴">
        <template slot-scope="scope">
          <span v-if="scope.row.overtime === undefined ||scope.row.overtime === null">-</span>
          <span v-else>{{ parseFloat(scope.row.overtime).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120" prop="attendanceDeductMoney" label="考勤日扣款">
        <template slot-scope="scope">
          <span v-if="scope.row.attendanceDeductMoney === undefined ||scope.row.attendanceDeductMoney === null">-</span>
          <span v-else>{{ parseFloat(scope.row.attendanceDeductMoney).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120" prop="leaveDeductMoney" label="事病假扣款">
        <template slot-scope="scope">
          <span v-if="scope.row.leaveDeductMoney === undefined ||scope.row.leaveDeductMoney === null">-</span>
          <span v-else>{{ parseFloat(scope.row.leaveDeductMoney).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="140" prop="elseDeductMoney" label="其他扣款">
        <template slot-scope="scope">
          <span v-if="scope.row.elseDeductMoney === undefined ||scope.row.elseDeductMoney === null">-</span>
          <span v-else>{{ parseFloat(scope.row.elseDeductMoney).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="140" prop="oneselfEndowmentInsurance" label="养老保险（个人）">
        <template slot-scope="scope">
          <span v-if="scope.row.oneselfEndowmentInsurance === undefined ||scope.row.oneselfEndowmentInsurance === null">-</span>
          <span v-else>{{ parseFloat(scope.row.oneselfEndowmentInsurance).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="140" prop="oneselfMedicalInsurance" label="医疗保险（个人）">
        <template slot-scope="scope">
          <span
            v-if="scope.row.oneselfMedicalInsurance === undefined ||scope.row.oneselfMedicalInsurance === null">-</span>
          <span v-else>{{ parseFloat(scope.row.oneselfMedicalInsurance).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="140" prop="oneselfUnemploymentInsurance"
                       label="失业保险（个人）">
        <template slot-scope="scope">
          <span
            v-if="scope.row.oneselfUnemploymentInsurance === undefined ||scope.row.oneselfUnemploymentInsurance === null">-</span>
          <span v-else>{{ parseFloat(scope.row.oneselfUnemploymentInsurance).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="140" prop="oneselfMaternityInsurance"
                       label="生育保险（个人）">
        <template slot-scope="scope">
          <span v-if="scope.row.oneselfMaternityInsurance === undefined ||scope.row.oneselfMaternityInsurance === null">-</span>
          <span v-else>{{ parseFloat(scope.row.oneselfMaternityInsurance).toFixed(2) }}</span>

        </template>
      </el-table-column>
      <el-table-column align="center" width="140" prop="oneselfInjuryInsurance"
                       label="工伤保险（个人）">
        <template slot-scope="scope">
          <span
            v-if="scope.row.oneselfInjuryInsurance === undefined ||scope.row.oneselfInjuryInsurance === null">-</span>
          <span v-else>{{ parseFloat(scope.row.oneselfInjuryInsurance).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="140" prop="oneselfHousingAllowance"
                       label="住房公积金（个人）">
        <template slot-scope="scope">
          <span
            v-if="scope.row.oneselfHousingAllowance === undefined ||scope.row.oneselfHousingAllowance === null">-</span>
          <span v-else>{{ parseFloat(scope.row.oneselfHousingAllowance).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="180" prop="amountInTotal" label="社保公积金合计（个人）">
        <template slot-scope="scope">
          <span v-if="scope.row.amountInTotal === undefined ||scope.row.amountInTotal === null">-</span>
          <span v-else>{{ parseFloat(scope.row.amountInTotal).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120" prop="payTaxesPay" label="个税">
        <template slot-scope="scope">

          <span v-if="scope.row.payTaxesPay === undefined ||scope.row.payTaxesPay === null">-</span>
          <span v-else>{{ parseFloat(scope.row.payTaxesPay).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120" prop="grossWage" label="应发工资">
        <template slot-scope="scope">
          <span v-if="scope.row.grossWage === undefined ||scope.row.grossWage === null">-</span>
          <span v-else>{{ parseFloat(scope.row.grossWage).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120" prop="netPayroll" label="实发工资">
        <template slot-scope="scope">
          <span v-if="scope.row.netPayroll === undefined ||scope.row.netPayroll === null">-</span>
          <span v-else>{{ parseFloat(scope.row.netPayroll).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120" prop="grantStatus" label="状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.grantStatus === '0'" type="info">未发放</el-tag>
          <el-tag v-if="scope.row.grantStatus === '1'" type="success">已发放</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" width="160" label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="grantSalarySheet(scope.row)">发放工资条</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList()"
    />
    <el-dialog title="发放工资条" :visible.sync="grantVisible" width="30%" center>
      <el-form style="margin-left: 40px" :rules="mapRules" ref="mapForm" label-position="top" label-width="130px"
               :model="map">
        <el-form-item prop="userName" label="选择发件邮箱">
          <el-select v-model="map.userName" placeholder="请选择">
            <el-option
              v-for="item in issueEmailList"
              :key="item.id"
              :label="item.userName"
              :value="item.userName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择展示工资项">
          <el-table ref="Single" @selection-change="fieldsChange" :data="Head" border>
            <el-table-column align="center" type="selection" width="55"></el-table-column>
            <el-table-column align="center" prop="webFields" label="工资项"></el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="grantVisible = false">取 消</el-button>
        <el-button type="primary" @click="previewDialog">预览</el-button>
      </div>

    </el-dialog>
    <el-dialog title="预览" :visible.sync="previewVisible" center>
      <h2> {{ parseInt(parseTime(queryParams.createTime, '{y}-{m}')) }} 月工资</h2>
      <hr>
      <br>
      <el-form style="margin-left: 40px" label-position="right" ref="previewForm" :rules="mapRules" label-width="130px"
               :model="map">
        <el-form-item label="发件邮箱">
          {{ map.userName }}
        </el-form-item>
        <el-form-item prop="email" label="收件邮箱">
          <el-input style="width: 320px" v-model="map.email"></el-input>
        </el-form-item>
      </el-form>
      <br>
      <hr>
      <h2>工资明细</h2>
      <el-table id="tables" :data="tableLabels" border>
        <el-table-column
          align="center"
          v-for="item in tableHead"
          :prop="item.sqlFields"
          :label="item.webFields">
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewVisible = false">取 消</el-button>
        <el-button type="primary" @click="send">预览</el-button>
      </div>
    </el-dialog>
    <el-drawer
      size="60%"
      :visible.sync="emailPre"
      direction="ttb"
      :before-close="beforeCloseEmail">
      <div id="mt">
        <table
          style="table-layout: fixed;width: 100%;border-spacing: 0px;border-right:1px solid #aaa;border-bottom:1px solid #aaa;">
          <thead>
          <tr style="background: #339;color: #ffffff;text-align: center">
            <th v-if="i === 0"
                style="width:140px;left: 0;position:sticky;top:0;border-left:1px solid #aaa;border-top:1px solid #aaa;padding:10px;"
                v-for="(head,i) in responseTable.head">
              {{ head }}
            </th>
            <th v-if="i !== 0"
                style="width:140px;position:sticky;top:0;border-left:1px solid #aaa;border-top:1px solid #aaa;padding:10px;"
                v-for="(head,i) in responseTable.head">
              {{ head }}
            </th>
          </tr>
          </thead>
          <tbody>
          <tr style="color: black;text-align: center">
            <td v-if="i === 0"
                style="width:140px;left: 0;position:sticky;border-left:1px solid #aaa;border-top:1px solid #aaa;padding:10px;"
                v-for="(content,i) in responseTable.content">
              {{ content }}
            </td>
            <td v-if="i !== 0"
                style="width:140px;position:sticky;border-left:1px solid #aaa;border-top:1px solid #aaa;padding:10px;"
                v-for="(content,i) in responseTable.content">
              {{ content }}
            </td>
          </tr>
          </tbody>
        </table>
      </div>
      <br>
      <div style="text-align: center">
        <el-button type="primary" @click="emailOn">发送</el-button>
        <el-button @click="beforeCloseEmail">取 消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
  import {salarySheetList, getTableHeadList, getTableHead, updateGrantStatus} from '@/api/system/collect'
  import Template from "@/views/system/email/ItoTemplate";
  import {sendEmail} from '@/api/system/email';
  import {
    selectList
  } from "@/api/system/issueEmail";
  import {parseTime} from '@/utils/ruoyi'

  Date.prototype.format = function (fmt) {
    var o = {
      "M+": this.getMonth() + 1, //月份
      "d+": this.getDate(), //日
      "h+": this.getHours(), //小时
      "m+": this.getMinutes(), //分
      "s+": this.getSeconds(), //秒
      "q+": Math.floor((this.getMonth() + 3) / 3), //季度
      "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
      if (new RegExp("(" + k + ")").test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
      }
    }
    return fmt;
  }
  export default {
    name: "salarySheet",
    components: {Template},
    data() {
      return {
        map: {
          title: '',
          userName: '',
          email: '',
          content: ''
        },
        payllAccounting: {},
        issueEmailList: [],
        previewVisible: false,
        Head: [],
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          all: '',
          createTime: new Date(new Date()).format("yyyy-MM-dd")
        },
        tableLabels: [],
        tableHead: [],
        total: 0,
        loading: false,
        indexCollectList: [],
        grantVisible: false,
        fieldsIds: [],
        responseTable: {
          head: [],
          content: []
        },
        emailPre: false,
        mapRules: {
          userName: [
            {required: true, message: '请选择发件邮箱', trigger: 'change'}
          ],
          email: [
            {required: true, message: '收件邮箱不能为空', trigger: 'blur'},
            {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}
          ]
        }
      }
    },
    created() {
      this.getList()
      this.getTableHead()
    },
    methods: {
      emailOn() {
        this.$confirm('是否确认发放' + this.payllAccounting.empName + '的工资单', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          var mt = document.getElementById('mt').innerHTML;
          this.map.title = this.payllAccounting.empName + parseInt(parseTime(this.queryParams.createTime, '{m}')) + '月工资单'
          this.map.content = encodeURIComponent(mt)
          sendEmail(this.map).then(res => {
            updateGrantStatus(this.payllAccounting.cId).then(res => {
              loading.close();
              this.emailPre = false
              this.grantVisible = false
              this.previewVisible = false
              this.$modal.msgSuccess("工资条已发放");
              this.allQuery()
            })
          }).catch(e => {
            loading.close();
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
      },
      beforeCloseEmail() {
        this.map.content = ''
        this.responseTable = {
          head: [],
          content: []
        }
        this.emailPre = false
      },
      send() {
        this.$refs['previewForm'].validate(valid => {
          if (valid) {
            var aa = document.getElementById('tables').innerText;
            let sp = aa.split("\n")
            for (let i = 0; i < sp.length; i++) {
              this.responseTable.head = sp[0].split("\t")
              if (i !== 0 && i % 2 !== 0) {
                this.responseTable.content.push(sp[i].split("\t")[0])
              }
            }
            this.emailPre = true
          }
        })
      },
      fieldsChange(val) {
        this.fieldsIds = val.map(m => m.id)
      },
      grantSalarySheet(row) {
        this.payllAccounting = row
        selectList().then(res => {
          this.issueEmailList = res.data
          this.grantVisible = true
        })
        this.getTableHead()
      },
      getTableHead() {
        getTableHead().then(res => {
          this.Head = res.data
        })
      },
      getHead() {
        getTableHeadList(this.fieldsIds).then(res => {
          this.tableHead = res.data
          if (this.payllAccounting.meritPay === null){
            this.payllAccounting.meritPay =0
          }
          if (this.payllAccounting.royaltiesMoney === null){
            this.payllAccounting.royaltiesMoney = 0
          }
          this.tableLabels[0] = this.payllAccounting
        })
      },
      previewDialog() {
        this.$refs['mapForm'].validate(valid => {
          if (valid) {
            if (this.fieldsIds.length > 0) {
              this.map.email = this.payllAccounting.mailbox;
              this.getHead()
              this.previewVisible = true
            } else {
              this.$message({
                type: 'warning',
                message: '请选择展示工资项!'
              });
            }
          }
        })
      },
      indexCreateTimeChange() {

      },
      getList() {
        this.loading = true
        salarySheetList(this.queryParams).then(res => {
          this.indexCollectList = res.rows
          this.total = res.total
          this.loading = false
        })
      },
      allQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      resetQuery() {
        this.queryParams.all = ''
        this.allQuery()
      },
      handleSelectionChange() {

      }
    }

  }
</script>

<style scoped>
  .el-drawer.ttb {
    overflow: scroll
  }
</style>
